package com.wwwarehouse.contract.convert_to_pc;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.bean.response.GetImportToolIndexBean;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.eventbus_event.CardDeskEvent;
import com.wwwarehouse.common.eventbus_event.PushImportEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.rsa.StringUtils;
import com.wwwarehouse.contract.bean.PushImportBean;
import com.wwwarehouse.contract.core.ContractConstant;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

/**
 * Created by feng.gao on 2017/9/7.
 */
@Route(path = "/contract/DurationTimeFragment")
public class DurationTimeFragment extends BaseFragment implements View.OnClickListener, NoHttpUtils.OnResponseListener {
	private long mSeconds; //起始时间，秒
	private TextView mTimeTv;
	private Timer timer;
	private TimerTask timerTask;
	private long cnt;
	public static final int GET_TIME_CODE = 0;
	private long mTimeCost;
	private String mTitle;
	private String mUrl;
	private TextView mUrlTv;

	GetImportToolIndexBean bean;
	private long mOperationUkid;
	@Override
	public void setTitle() {
		if (peekFragment() instanceof DurationTimeFragment) {
			if (!TextUtils.isEmpty(mTitle) && !TextUtils.isEmpty(getZhString(mTitle))) {
				mActivity.setTitle(getZhString(mTitle));
			} else {
				mActivity.setTitle(R.string.import_with_sort_title);
			}
		}
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		return inflater.inflate(R.layout.duration_time_fragment, container, false);
	}
	private String getZhString(String eng) {
		if (eng.equals("IMPORT_TOOL")) {
			return "导入设备信息";
		}
		if (eng.equals("IMPORT_GOODS")) {
			return "导入商品信息";
		}
		if (eng.equals("IMPORT_RS_STORE")) {
			return "导入仓储信息";
		}
		if (eng.equals("IMPORT_RS_LABOUR")) {
			return "导入劳务信息";
		}
		if (eng.equals("IMPORT_RS_SALE")) {
			return "导入供货信息";
		}
		if (eng.equals("IMPORT_RS_TRANSPORT")) {
			return "导入运输信息";
		}
		return "";
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		EventBus.getDefault().register(this);
		mTimeTv = (TextView) view.findViewById(R.id.time_task_view);
		mUrlTv = (TextView) view.findViewById(R.id.url_tv);
		view.findViewById(R.id.btn_confirm).setOnClickListener(this);
		timer = new Timer();
		if (getArguments() != null && getArguments().getSerializable(Constant.KEY_INTENT_IMPORT_TIME) != null) {
			bean = (GetImportToolIndexBean) getArguments().getSerializable(Constant.KEY_INTENT_IMPORT_TIME);
			if (bean != null) {
				mTimeCost = bean.getTimeCost();
//				mOperationUkid = bean.getOperationUkid();
				cnt = mTimeCost;
				startClick();
			}
		} else {
			if (getArguments() != null) {
				mTimeCost = getArguments().getLong(ContractConstant.KEY_BUNDLE_PUSH_TO_DUTATIONTIME);
//				mOperationUkid = bean.getOperationUkid();
				cnt = mTimeCost;
				startClick();
			}
		}
		if (getArguments() != null && getArguments().getString(Constant.KEY_INTENT_IMPORT_TYPE) != null) {
			mTitle = getArguments().getString(Constant.KEY_INTENT_IMPORT_TYPE);
		}
		if (getArguments() != null && StringUtils.isNoneNullString(getArguments().getString(Constant.KEY_PC_IMPORT_UNIFY_SHORT_URL))) {
			mUrl = getArguments().getString(Constant.KEY_PC_IMPORT_UNIFY_SHORT_URL);
			if (StringUtils.isNoneNullString(mUrl)) {
//				mUrlTv.setText(mUrl);
			}
		}

//		startClick();
	}

	@Override
	public void requestDatas() {
		//请求开始时间
//		Map<String, String> map = new HashMap<>();
//		map.put("operationUkid", mOperationUkid);
//		NoHttpUtils.httpPost(ContractConstant.GET_START_TIME , map ,  this ,GET_TIME_CODE );
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_confirm) {
			EventBus.getDefault().post(new CardDeskEvent("clear_back_stack"));
		}
	}
//	/**
//	 * 根据开始时间获取持续时间
//	 * @param begin
//	 */
//	private void getTimeBetween(long begin) {
//		Date end =  new Date(System.currentTimeMillis());
//		long endSeconds = end.getTime() / 1000;
//		long between=(endSeconds-begin);
//		cnt = between;
//		startClick();
//	}


	/**
	 * 格式化时间
	 * @param cnt
	 * @return
	 */
	private String getStringTime(long cnt) {
		long hour = cnt / 3600;
		long min = cnt % 3600 / 60;
		long second = cnt % 60;
		return String.format(Locale.CHINA, "%02d:%02d:%02d", hour, min, second);
	}


	/**
	 * 开始计时
	 */
	public void startClick() {
		timerTask = new TimerTask() {
			@Override
			public void run() {
				mActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mTimeTv.setText(getStringTime(cnt++));

					}
				});
			}
		};
		timer.schedule(timerTask, 0, 1000);
	}


	@Override
	public void onSucceed(CommonClass commonClass, int i) {
		if (i == GET_TIME_CODE) {
//			if (commonClass != null && commonClass.getData() != null) {
//				try {
//					String date = commonClass.getData().toString();
//					Date beginTime = stringToDate(date, "yyyy-MM-dd HH:mm:ss");
//					getTimeBetween(beginTime);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
		}
	}

	@Override
	public void onFailed(String s, int i) {

	}

	@Override
	public void onFinish(int i) {

	}

	/**
	 * 接收推送消息，跳转到导入成功页面。
	 * @param pushImportEvent
	 */
	public void onEventMainThread(PushImportEvent pushImportEvent){
		if (peekFragment() instanceof DurationTimeFragment) {
			PushImportBean pushImportBean = JSON.parseObject(pushImportEvent.getResult(), PushImportBean.class);
			if (pushImportBean != null && pushImportBean.getMsg() != null ) {
				Bundle bundle = new Bundle();
				if (!TextUtils.isEmpty(pushImportBean.getMsg().getPushImportCount())) {
					bundle.putLong(Constant.KEY_INTENT_IMPORT_TOOL_PUSH_CLICK, Long.valueOf(pushImportBean.getMsg().getPushImportCount()));
				}
				if (StringUtils.isNoneNullString(mTitle)) {
					bundle.putString(Constant.KEY_INTENT_IMPORT_TYPE , mTitle);
				}
				ImportSuccessFragment importSuccessFragment = new ImportSuccessFragment();
				importSuccessFragment.setArguments(bundle);

				popFragment();

				pushFragment(importSuccessFragment);
			}
		}
	}


	@Override
	public void onDestroy() {
	        super.onDestroy();
	        EventBus.getDefault().unregister(this);
	    }




	/**
	 * string转Data
	 * @param strTime 要转换的string类型的时间
	 * @param formatType 要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd HH时mm分ss秒
	 * @return Date
	 */
	public static Date stringToDate(String strTime, String formatType) {
		SimpleDateFormat formatter = new SimpleDateFormat(formatType);
		Date date = null;
		try {
			date = formatter.parse(strTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}


}
